'use strict';

const BaseService = require('./base');
const crypto = require('crypto');

class WechatService extends BaseService {

    

    /**
     * 登录授权
     */
    async code2Session(code) {
        const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${this.config.wechatConfig.appId}&secret=${this.config.wechatConfig.appSecret}&js_code=${code}&grant_type=authorization_code`
        const res = await this.ctx.curl(url, {
            dataType: 'json'
        });
        if ('errcode' in res.data && res.data.errcode != 0) {
            this.ctx.helper.commonErr(res.data.errmsg, {
                returnCode: res.data.errcode
            });
        }
        
        return res.data;
    }
    
    /**
     * 解密
     */
    async decryptData(code, encryptedData, iv) {
        const info = await this.code2Session(code);
        var sessionKey = Buffer.from(info.session_key, 'base64');
        encryptedData = Buffer.from(encryptedData, 'base64');
        iv = Buffer.from(iv, 'base64');
        
        try {
            // 解密
            var decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv);
            // 设置自动 padding 为 true，删除填充补位
            decipher.setAutoPadding(true);
            var decoded = decipher.update(encryptedData, 'binary', 'utf8');
            // console.log(decipher.final('utf8'));
            decoded += decipher.final('utf8');
           
            decoded = JSON.parse(decoded);

        } catch (err) {
            this.ctx.helper.commonErr("Illegal Buffer");
        }

        if (decoded.watermark.appid !== this.config.wechatConfig.appId) {
            this.ctx.helper.commonErr("Illegal Buffer");
        }
        await this.app.redis.set(decoded.phoneNumber, info.openid, "EX", this.config.redis.redisExpire)
        return decoded;
    }

    /**
     * 订阅消息
     */
    async send(openid) {
        const accessToken = await this.getAccessToken();
        const url = `https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${accessToken}`;
        const res = await this.ctx.curl(url, {
            method: "POST",
            data: {
                "touser": openid,
                "template_id": "TEMPLATE_ID",
                "page": "index",
                "miniprogram_state":"developer",
                "lang":"zh_CN",
                "data": {
                    "number01": {
                        "value": "339208499"
                    },
                    "date01": {
                        "value": "2015年01月05日"
                    },
                    "site01": {
                        "value": "TIT创意园"
                    } ,
                    "site02": {
                        "value": "广州市新港中路397号"
                    }
                }
            }
        })
        if ('errcode' in res.data && res.data.errcode != 0) {
            this.ctx.helper.commonErr(res.data.errmsg, {
                returnCode: res.data.errcode
            });
        }
        return res.data;
    }

    /**
     * 接口调用凭证
     */
    async getAccessToken() {
        const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.config.wechatConfig.appId}&secret=${this.config.wechatConfig.appSecret}`;
        const res = await this.ctx.curl(url, {
            dataType: 'json'
        });
        if ('errcode' in res.data && res.data.errcode != 0) {
            this.ctx.helper.commonErr(res.data.errmsg, {
                returnCode: res.data.errcode
            });
        }
        return res.data;
    }

    /**
     * 统一下单
     */
    async transactionPay(openid, out_trade_no, total, description = '', notify_url = '') {
        const url = 'https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi';
        const res = await this.ctx.curl(url, {
            method: 'POST',
            data: {
                appid: this.config.wechatConfig.appId,
                mchid: this.config.wechatConfig.mchid,
                description: description,
                out_trade_no: out_trade_no,
                notify_url: notify_url,
                amount: {
                    total: total * 100
                },
                payer: {
                    openid: openid
                }
                
            }
        })
        console.log(res);
    }

}

module.exports = WechatService;